class StoreProduct < ApplicationRecord
  belongs_to :store
  has_many :images, class_name: "StoreImage", as: :imageable
  belongs_to :store_product_category, touch: true
  has_many :cart_items
  belongs_to :store_customer

  scope :showable, -> { where(showable: true) }
  scope :useable, -> { where(useable: true) }
  scope :customs, -> { where(customable: true) }
  scope :uncustoms, -> { where(customable: false) }
  scope :by_user, ->(user_id) { where(store_customer_id: user_id) if user_id.present? }
  scope :by_name, ->(name) { where("store_products.name LIKE ?", "%#{name}%") }

  accepts_nested_attributes_for :images

  def unuse!
    self.update!(useable: false)
  end

  def url
    images.first.url
  end

  def sale_price
    if vipable && vip_price
      vip_price
    else
      price
    end
  end

  def old_price
    if vipable && vip_price
      "￥#{price}"
    end
  end

  def toggle!
    self.update!(showable: !self.showable)
  end

end
